<?php
class ControllerSettingTemplate extends Controller {
	private $error = array();

	public function index() {
		$this->load->language('common/header');
		$this->load->language('setting/template');
			
		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('setting/template');

		$this->getList();
	}

	public function insert() {
		$this->load->language('common/header');
		$this->load->language('setting/template');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('setting/template');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_setting_template->addTemplate($this->request->post);

			$this->session->data['success'] = $this->language->get('text_success');

			$this->redirect($this->url->link('setting/template', 'token=' . $this->session->data['token'] . $this->url(), 'SSL'));
		}

		$this->getForm();
	}

	public function update() {
		$this->load->language('common/header');
		$this->load->language('setting/template');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('setting/template');

		if (($this->request->server['REQUEST_METHOD'] == 'POST') && $this->validateForm()) {
			$this->model_setting_template->editTemplate($this->request->get['template_id'], $this->request->post);

			$this->session->data['success'] = $this->language->get('text_success');

			$this->redirect($this->url->link('setting/template', 'token=' . $this->session->data['token'] . $this->url(), 'SSL'));
		}

		$this->getForm();
	}

	public function delete() {
		$this->load->language('setting/template');

		$this->document->setTitle($this->language->get('heading_title'));

		$this->load->model('setting/template');

		if (isset($this->request->post['selected']) && $this->validateDelete()) {
			foreach ($this->request->post['selected'] as $template_id) {
				$this->model_setting_template->deleteTemplate($template_id);
			}

			$this->session->data['success'] = $this->language->get('text_success');

			$this->redirect($this->url->link('setting/template', 'token=' . $this->session->data['token'] . $this->url(), 'SSL'));
		}

		$this->getList();
	}

	private function getList() {
		if (isset($this->request->get['filter_name'])) {
			$filter_name = $this->request->get['filter_name'];
		} else {
			$filter_name = null;
		}

		if (isset($this->request->get['filter_type'])) {
			$filter_type = $this->request->get['filter_type'];
		} else {
			$filter_type = null;
		}

		if (isset($this->request->get['filter_restaurant_name'])) {
			$filter_restaurant_name = $this->request->get['filter_restaurant_name'];
		} else {
			$filter_restaurant_name = null;
		}

		if (isset($this->request->get['filter_status'])) {
			$filter_status = $this->request->get['filter_status'];
		} else {
			$filter_status = null;
		}

		$this->data['breadcrumbs'] = array();

		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
			'separator' => false
		);
		
		
		$this->data['breadcrumbs'][] = array(
			'text'      => $this->language->get('text_system'),
   			'href'      => '#',
   			'separator' => ' :: '
   		);
		
		$this->data['breadcrumbs'][] = array(
			'text'      => $this->language->get('text_design'),
   			'href'      => '#',
   			'separator' => ' :: '
		);
			
		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_template'),
			'href'      => '#',
      		'separator' => ' :: '
		);

		$this->data['insert'] = $this->url->link('setting/template/insert', 'token=' . $this->session->data['token'] . $this->url(), 'SSL');
		$this->data['delete'] = $this->url->link('setting/template/delete', 'token=' . $this->session->data['token'] . $this->url(), 'SSL');
		 
		$this->data['templates'] = array();

		$page = isset($this->request->get['page']) ? $this->request->get['page'] : 1;
		$sort = isset($this->request->get['sort']) ? $this->request->get['sort'] : 't.name';
		$order = isset($this->request->get['order']) ? $this->request->get['order'] : 'ASC';

		$data = array(
			'filter_name'	  => $filter_name, 
			'filter_type'	  => $filter_type,
			'filter_restaurant_name'	  => $filter_restaurant_name,
			'filter_status'   => $filter_status,
			'sort'            => $sort,
			'order'           => $order,
			'start'           => ($page - 1) * $this->config->get('config_admin_limit'),
			'limit'           => $this->config->get('config_admin_limit')
		);

		$this->load->model('setting/image');

		$template_total = $this->model_setting_template->getTotalTemplates($data);
		 
		$results = $this->model_setting_template->getTemplates($data);

		$this->load->model('restaurant/restaurant');

		foreach ($results as $result) {
			$action = array();

			$action[] = array(
				'text' => $this->language->get('text_edit'),
				'href' => $this->url->link('setting/template/update', 'token=' . $this->session->data['token'] . '&template_id=' . $result['template_id'] . $this->url(), 'SSL')
			);

			if (file_exists(DIR_IMAGE . "templates/" . $result['directory'] . ".png")) {
				$image = $this->model_setting_image->resize("/templates/" . $result['directory'] . ".png", 100, 100);
			} else {
				$image = $this->model_setting_image->resize('no_image.jpg', 100, 100);
			}

			$restaurants = $this->model_restaurant_restaurant->getRestaurantsByTemplateId($result['template_id']);
			$restaurant_name = "";
			foreach ($restaurants as $restaurant) {
				if(!empty($restaurant_name)) {
					$restaurant_name .= ", ";
				}
				$restaurant_name .= $restaurant['name'];
			}

			$this->data['templates'][] = array(
				'template_id' => $result['template_id'],
				'name'        => $result['name'],
				'type'        =>  ($result['type'] ? $this->language->get('text_private') : $this->language->get('text_public')),
				'restaurant_name'  => $restaurant_name,
      			'image'		  => $image,
				'inUse'		  => $result['inUse'],
				'status'      => ($result['status'] ? $this->language->get('text_enabled') : $this->language->get('text_disabled')),
				'selected'    => isset($this->request->post['selected']) && in_array($result['template_id'], $this->request->post['selected']),
				'action'      => $action
			);
		}

		// Mapping all language variables
		$this->data = array_merge($this->data, $this->language->getData());
		 
		$this->data['token'] = $this->session->data['token'];

		if (!isset($this->error['warning'])) {
			$this->data['error_warning'] = '';
		}
			
		if (isset($this->error['template_in_use'])) {
			$this->data['error_template_in_use'] = $this->error['template_in_use'];
		} else {
			$this->data['error_template_in_use'] = array();
		}

		if (isset($this->session->data['success'])) {
			$this->data['success'] = $this->session->data['success'];

			unset($this->session->data['success']);
		} else {
			$this->data['success'] = '';
		}

		$this->data['sort_name'] = $this->url->link('setting/template', 'token=' . $this->session->data['token'] . $this->url('t.name'), 'SSL');
		$this->data['sort_type'] = $this->url->link('setting/template', 'token=' . $this->session->data['token'] . $this->url('t.type'), 'SSL');
		$this->data['sort_status'] = $this->url->link('setting/template', 'token=' . $this->session->data['token'] . $this->url('t.status'), 'SSL');

		$pagination = new Pagination();
		$pagination->total = $template_total;
		$pagination->page = $page;
		$pagination->limit = $this->config->get('config_admin_limit');
		$pagination->text = $this->language->get('text_pagination');
		$pagination->url = $this->url->link('setting/template', 'token=' . $this->session->data['token'] . $this->url(), 'SSL');
		 
		$this->data['pagination'] = $pagination->render();

		$this->data['filter_name'] = $filter_name;
		$this->data['filter_type'] = $filter_type;
		$this->data['filter_restaurant_name'] = $filter_restaurant_name;
		$this->data['filter_status'] = $filter_status;

		$this->data['sort'] = $sort;
		$this->data['order'] = $order;

		$this->template = 'setting/template_list.tpl';
		$this->children = array(
			'common/header',
			'common/footer'
		);

		$this->response->setOutput($this->render());
	}

	private function getForm() {
		// Mapping all language variables
		$this->data = array_merge($this->data, $this->language->getData());
			
		if (!isset($this->error['warning'])) {
			$this->data['error_warning'] = '';
		}

		if (!isset($this->error['name'])) {
			$this->data['error_name'] = '';
		}

		if (!isset($this->error['directory'])) {
			$this->data['error_directory'] = '';
		}

		if (!isset($this->error['directory_not_exist'])) {
			$this->data['error_directory_not_exist'] = '';
		}

		$this->data['breadcrumbs'] = array();

		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_home'),
			'href'      => $this->url->link('common/home', 'token=' . $this->session->data['token'], 'SSL'),
			'separator' => false
		);
		
		
		$this->data['breadcrumbs'][] = array(
			'text'      => $this->language->get('text_system'),
   			'href'      => '#',
   			'separator' => ' :: '
   		);
		
		$this->data['breadcrumbs'][] = array(
			'text'      => $this->language->get('text_design'),
   			'href'      => '#',
   			'separator' => ' :: '
		);
			
		$this->data['breadcrumbs'][] = array(
       		'text'      => $this->language->get('text_template'),
			'href'      => $this->url->link('setting/template', 'token=' . $this->session->data['token'] . $this->url(), 'SSL'),
      		'separator' => ' :: '
		);

		if (!isset($this->request->get['template_id'])) {
			$this->data['breadcrumbs'][] = array(
	       		'text'      => $this->language->get('heading_title_insert'),
				'href'      => '#',
	      		'separator' => ' :: '
			);
		} else {
			$this->data['breadcrumbs'][] = array(
				       		'text'      => $this->language->get('heading_title_update'),
							'href'      => '#',
				      		'separator' => ' :: '
			);
		}
		 
		if (!isset($this->request->get['template_id'])) {
			$this->data['action'] = $this->url->link('setting/template/insert', 'token=' . $this->session->data['token'] . $this->url(), 'SSL');
		} else {
			$this->data['action'] = $this->url->link('setting/template/update', 'token=' . $this->session->data['token'] . '&template_id=' . $this->request->get['template_id'] . $this->url(), 'SSL');
		}

		$this->data['cancel'] = $this->url->link('setting/template', 'token=' . $this->session->data['token'] . $this->url(), 'SSL');

		$this->data['token'] = $this->session->data['token'];

		if (isset($this->request->get['template_id']) && ($this->request->server['REQUEST_METHOD'] != 'POST')) {
			$template_info = $this->model_setting_template->getTemplate($this->request->get['template_id']);
		}

		if (isset($this->request->post['name'])) {
			$this->data['name'] = $this->request->post['name'];
		} elseif (!empty($template_info)) {
			$this->data['name'] = $template_info['name'];
		} else {
			$this->data['name'] = '';
		}

		if (isset($this->request->post['directory'])) {
			$this->data['directory'] = $this->request->post['directory'];
		} elseif (!empty($template_info)) {
			$this->data['directory'] = $template_info['directory'];
		} else {
			$this->data['directory'] = '';
		}
		 
		if (isset($this->request->post['type'])) {
			$this->data['type'] = $this->request->post['type'];
		} elseif (!empty($template_info)) {
			$this->data['type'] = $template_info['type'];
		} else {
			$this->data['type'] = "";
		}
		 
		if (isset($this->request->post['status'])) {
			$this->data['status'] = $this->request->post['status'];
		} else if (!empty($template_info)) {
			$this->data['status'] = $template_info['status'];
		} else {
			$this->data['status'] = 1;
		}

		$this->load->model('setting/image');

		if (file_exists(DIR_IMAGE . "templates/" . $this->data['directory'] . ".png")) {
			$image = $this->model_setting_image->resize("/templates/" . $this->data['directory'] . ".png", 200, 200);
		} else {
			$image = $this->model_setting_image->resize('no_image.jpg', 100, 100);
		}

		$this->data['image'] = $image;
		$this->data['no_image'] = $this->model_setting_image->resize('no_image.jpg', 100, 100);

		$this->load->model('restaurant/restaurant');

		if (isset($this->request->post['restaurants'])) {
			$this->data['restaurants'] = $this->request->post['restaurants'];
		} elseif (isset($this->request->get['template_id'])) {
			$this->data['restaurants'] = $this->model_restaurant_restaurant->getRestaurantsByTemplateId($this->request->get['template_id']);
		} else {
			$this->data['restaurants'] = array();
		}
		
		// Check restaurant in use
		$this->load->model('setting/setting');
		for ($i = 0; $i < sizeof($this->data['restaurants']); $i++) {
			$inUse = false;
			$data = array(
				'restaurant_id' => $this->data['restaurants'][$i]['restaurant_id'],
				'group'    => 'config',
				'key'      => 'config_template',
				'value'    => $this->request->get['template_id']
			);
			
			$inUse = $this->model_setting_setting->getTotalSettings($data) > 0;
			
			$this->data['restaurants'][$i]['inUse'] = $inUse;
		}

		$this->template = 'setting/template_form.tpl';
		$this->children = array(
			'common/header',
			'common/footer'
		);

		$this->response->setOutput($this->render());
	}

	private function validateForm() {
		if (!$this->user->hasPermission('modify', 'setting/template')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		if ((utf8_strlen($this->request->post['name']) < 3 || utf8_strlen($this->request->post['name']) > 255)) {
			$this->error['name'] = $this->language->get('error_name');
		}

		if ((utf8_strlen($this->request->post['directory']) < 1 || utf8_strlen($this->request->post['directory']) > 32)) {
			$this->error['directory'] = $this->language->get('error_directory');
		} else if(!file_exists(DIR_RESTAURANT . 'view/theme/' . $this->request->post['directory'])
				  || substr($this->request->post['directory'], 0, 6) === 'portal') {
			$this->error['directory_not_exist'] = $this->language->get('error_directory_not_exist');
		}

		if ($this->error && !isset($this->error['warning'])) {
			$this->error['warning'] = $this->language->get('error_warning');
		}

		if (!$this->error) {
			return true;
		} else {
			return false;
		}
	}

	private function validateDelete() {
		if (!$this->user->hasPermission('modify', 'setting/template')) {
			$this->error['warning'] = $this->language->get('error_permission');
		}

		$this->load->model('setting/setting');

		// Check if any template are currently in use
		foreach ($this->request->post['selected'] as $template_id) {
			$data = array(
				'group' => 'config',
				'key'   => 'config_template',
				'value' => $template_id
			);
				
			$total = $this->model_setting_setting->getTotalSettings($data);
				
			if($total > 0) {
				$this->error['template_in_use'][$template_id] = $this->language->get('error_template_in_use');
			}
		}

		if ($this->error && !isset($this->error['warning'])) {
			$this->error['warning'] = $this->language->get('error_warning');
		}

		if (!$this->error) {
			return true;
		} else {
			return false;
		}
	}

	private function url($sort = ''){
		$url = "";

		if (isset($this->request->get['filter_name'])) {
			$url .= '&filter_name=' . $this->request->get['filter_name'];
		}

		if (isset($this->request->get['filter_type'])) {
			$url .= '&filter_type=' . $this->request->get['filter_type'];
		}

		if (isset($this->request->get['filter_restaurant_name'])) {
			$url .= '&filter_restaurant_name=' . $this->request->get['filter_restaurant_name'];
		}

		if (isset($this->request->get['filter_status'])) {
			$url .= '&filter_status=' . $this->request->get['filter_status'];
		}

		if (isset($this->request->get['order'])) {
			$order = $this->request->get['order'];
		} else {
			$order = 'ASC';
		}

		if (isset($this->request->get['page'])) {
			$page = $this->request->get['page'];
		} else {
			$page = 1;
		}

		if(!empty($sort)) {
			if ($order == 'ASC') {
				$url .= '&order=DESC';
			} else {
				$url .= '&order=ASC';
			}

			$url .= '&sort=' . $sort;
		} else {

			if (isset($this->request->get['sort'])) {
				$url .= '&sort=' . $this->request->get['sort'];
			} else {
				$url .= '&sort=t.name';
			}

			if (isset($this->request->get['order'])) {
				$url .= '&order=' . $this->request->get['order'];
			}
		}

		$url .= '&page=' . $page;

		return $url;
	}
}
?>